package com.ktgj.flight.common.ruili;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.base.Strings;
import com.ktgj.common.core.enums.EnumHelper;
import com.ktgj.common.core.utils.*;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.flight.common.BaseClass;
import com.ktgj.flight.common.ruili.drdomain.*;
import com.ktgj.flight.common.ruili.drdomain.vo.OrderBookingSubmitVo;
import com.ktgj.flight.common.ruili.drdomain.vo.SearchPriceVo;
import com.ktgj.flight.common.pay._HuiFu;
import com.ktgj.flight.domain.InterfaceEntity.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author wyj
 * @create 2021-09-27 12:46
 */
@Service
public class _DR extends BaseClass {

    /*//正式环境:https://ota.rlair.net/
    private static final String urlDR = "https://ota.rlair.net/";
    private static final String password = "jinseshiji20180719";*/

    //测试环境:https://ota.test.rlair.net/
//    private static final String urlDR = "https://ota.test.rlair.net/";
//    private static final String password = "123456";


    //正式环境密码
    private static final String password = "jinseshiji20180719";
    //请求地址
    private static final String urlDR = "http://172.16.2.65:9528/";


    //请求Token用户名
    private static final String username = "jinseshiji";

    //获取Token秘钥方式
    private static final String grant_type = "password";

    //token_type默认模式
    private static String _token_type = "bearer";

    // 联系人
    private static final String contactName = "金色世纪";
    private static final String contactEmail = "jpxt@jsj.com.cn";
    private static final String MerId = "874035";

    //缓存token的key
    private static final String DR_TOKEN_KEY = "drTokenKey";

    @Autowired
    private RedisService redisService;


    private String data(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(date);
    }

    private String strOnlyCode = data(new Date()) + new Random().nextInt(10000) % (10000 - 1000 + 1) + 1000;

    /**
     * 航班查询
     */
    @Override
    public MoFlightSearchResponse _FlightSearch(MoFlightSearchRequest moRequest) {
        moRequest.OnlyCode = strOnlyCode;
        MoFlightSearchResponse response = new MoFlightSearchResponse();
        response.OnlyCode = moRequest.OnlyCode;
        response.ProviderCode = moRequest.ProviderCode;
        response.RequestType = moRequest.RequestType;

        String strRequestData = "";
        String strResponseData = "";
        Date requestTime = new Date();
        Date returnTime = new Date();

        String tokenKey = null;
        try {
            tokenKey = this._GetToken();
        } catch (IOException e) {
            e.printStackTrace();
        }
        DrToken drToken = new DrToken(tokenKey, _token_type);
        try {
            int Logo = 0;
            for (int i = 0; i < moRequest.TripType; i++) {
                if (Strings.isNullOrEmpty(tokenKey)) return null;

                drToken.ServerUrl = String.format(urlDR + "FlightQuery/QuerySeatFromOTA?DepartureIataCode=" + moRequest.GoSearchWhere.OrgAirport + "&ArrivalIataCode=" + moRequest.GoSearchWhere.DstAirport + "&FlightDate=" + moRequest.GoSearchWhere.DepDate + "&TravelType=OW");
                if (moRequest.TripType == 2) {
                    if (Logo == 0) {
                        drToken.ServerUrl = String.format(urlDR + "FlightQuery/QuerySeatFromOTA?RouteIndex=0&DepartureIataCode=" + moRequest.GoSearchWhere.OrgAirport + "&ArrivalIataCode=" + moRequest.GoSearchWhere.DstAirport + "&FlightDate=" + moRequest.GoSearchWhere.DepDate + "&TravelType=RT");
                        Logo = 1;
                    } else if (Logo == 1) {
                        drToken.ServerUrl = String.format(urlDR + "FlightQuery/QuerySeatFromOTA?RouteIndex=1&DepartureIataCode=" + moRequest.BackSearchWhere.OrgAirport + "&ArrivalIataCode=" + moRequest.BackSearchWhere.DstAirport + "&FlightDate=" + moRequest.BackSearchWhere.DepDate + "&TravelType=RT");
                    }
                }
                //航班旅行类别 OW单程  RT往返  CT联程多段
                strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", drToken.Token_type, drToken.Access_token, "application/json", "GET", "", 60 * 1000, false);

                if (strResponseData.equals(null) && strRequestData.equals("")) {
                    response.ErrorCode = (EnumHelper.ReturnCode.请求接口异常).toString();
                    response.ErrorMsg = "航班查询，未返回数据";
                    response.IsSuccess = false;
                    return response;
                }
            }
            // 判断是否是基类错误
            DrResponsestatus baseResponse = JSON.parseObject(strResponseData, DrResponsestatus.class);
            if (!baseResponse.IsSuccess) {
                response.ErrorCode = (EnumHelper.ReturnCode.失败).toString();
                response.ErrorMsg = baseResponse.Msg;
                response.IsSuccess = false;
                return response;
            }

            // 验价实体处理
            DrFlightSearch drResponse = JSON.parseObject(strResponseData, DrFlightSearch.class);
            if (drResponse.ResponseStatus != null) {
                if (!drResponse.ResponseStatus.IsSuccess) {
                    response.ErrorCode = (EnumHelper.ReturnCode.请求接口异常).toString();
                    response.ErrorMsg = "航班查询，未成功";
                    response.IsSuccess = false;
                    return response;
                }
            }

            //开始解析瑞丽返回的航班数据
            // 逻辑处理
            // 解析航班 FlightListGroupList/FlightListGroup
            /**
             * 获取查询结果缓存Id
             * */
            response.Piid = drResponse.Data.QueryResultGuid;
            /**
             * 获取产品代码
             * */
            for (QueryResultFlightList queryResultFlightList : drResponse.Data.QueryResultFlightList) {
                for (QueryResultSegmentList queryResultSegmentList : queryResultFlightList.QueryResultSegmentList) {
                    for (QueryResultProductList queryResultProductList : queryResultSegmentList.QueryResultProductList) {
                        response.ProviderCode = queryResultProductList.ProductBasicInfo.ProductCode;
                    }
                }
                if (!response.ProviderCode.equals(null) && !response.ProviderCode.equals("")) {
                    break;
                }
            }

            for (QueryResultFlightList nf : drResponse.Data.QueryResultFlightList) {
                for (QueryResultSegmentList rs : nf.QueryResultSegmentList) {
                    MoFlightInfo finfo = new MoFlightInfo();
                    finfo.Airline = rs.Airline;
                    finfo.FlightNo = rs.FlightNo;
                    finfo.PlaneStyle = rs.PlaneModel;

                    finfo.OrgAirport = rs.OrgCity;
                    finfo.DstAirport = rs.DstCity;
                    finfo.DepTerm = rs.DepartureTerminal;
                    finfo.ArrTerm = rs.ArriveTerminal;

                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    String[] depDateTime = rs.DepartureTime.split("T");
                    String[] arrDateTime = rs.ArriveTime.split("T");

                    finfo.DepDate = dateFormat.parse(depDateTime[0] + " " + depDateTime[1]);
                    finfo.ArrDate = dateFormat.parse(arrDateTime[0] + " " + arrDateTime[1]);
                    finfo.IsCodeShare = rs.CodeShare;
                    finfo.Carrier = rs.FlightNo;
                    finfo.StopCount = rs.StopNumber;

                    finfo.Cabin = moRequest.GoSearchWhere.Cabin;

                    //解析经济舱，公务舱，头等舱的全价
                    for (QueryResultProductList rp : rs.QueryResultProductList) {
                        for (PassengerFareList pf : rp.PassengerFareList) {
                            MoCabinInfo cinfo = new MoCabinInfo();
                            String strCabinClass = pf.ClassCode;
                            BigDecimal FullAmount = pf.AdultFare.Price;
                            if ("Y".equals(strCabinClass)) {
                                finfo.FullAmountY = FullAmount;
                            }
                            if ("C".equals(strCabinClass)) {
                                finfo.FullAmountC = FullAmount;
                            }
                            if ("F".equals(strCabinClass)) {
                                finfo.FullAmountF = FullAmount;
                            }
                            cinfo.ProductPolicy.StrProductType = rp.ProductBasicInfo.ProductCode;
                            cinfo.CallCenterAmountInfo.OrgTicketAmount = FullAmount;
                            //基建燃油费
                            finfo.FuelTax = pf.AdultFare.FuelTax;
                            finfo.AirportTax = pf.AdultFare.AirportTax;

                            if (pf.FollowChildFare != null)//跟随成人价格
                            {
                                //cinfo.ChdCabin = new com.ktgj.flight.domain.InterfaceEntity.CabinPassenger();
                                cinfo.CallCenterAmountInfo.OrgChdTicketAmount = pf.FollowChildFare.Price;
                                //儿童基建燃油费
                                finfo.ChildAirportTax = pf.FollowChildFare.AirportTax;
                                finfo.ChildFuelTax = pf.FollowChildFare.FuelTax;
                                /*cinfo.ChdCabin.Cabin = pf.ClassCode;
                                cinfo.ChdCabin.follow = true;*/
                            } else if (pf.UnFollowChildFare != null) //不跟随成人价格
                            {
                                //cinfo.ChdCabin = new com.ktgj.flight.domain.InterfaceEntity.CabinPassenger();
                                cinfo.CallCenterAmountInfo.OrgChdTicketAmount = pf.UnFollowChildFare.Price;
                                //儿童基建燃油费
                                finfo.ChildAirportTax = pf.UnFollowChildFare.AirportTax;
                                finfo.ChildFuelTax = pf.UnFollowChildFare.FuelTax;
                                /*cinfo.ChdCabin.Cabin = pf.ClassCode;
                                cinfo.ChdCabin.follow = false;*/
                            }

                            if (pf.InfantFare != null)//婴儿价格
                            {
                                //cinfo.InfCabin = new com.ktgj.flight.domain.InterfaceEntity.CabinPassenger();
                                cinfo.CallCenterAmountInfo.OrgIftTicketAmount = pf.InfantFare.Price;
                                //婴儿基建燃油费
                                finfo.InfantFuelTax = pf.InfantFare.FuelTax;
                                finfo.InfantAirportTax = pf.InfantFare.AirportTax;
                                //cinfo.InfCabin.Cabin = pf.ClassCode;
                            }

                            //获取当前舱位
                            QueryResultSeatClassList sc = rs.QueryResultSeatClassList.stream().filter(a -> Objects.equals(a.ClassCode, pf.ClassCode)).findFirst().orElse(null);
                            //解析舱位和剩余座位
                            if (sc != null) {
                                cinfo.Cabin = sc.ClassCode;

                                cinfo.CabinLeft = sc.AvailableNumber;
                                BigDecimal count = new BigDecimal(0);
                                if (FullAmount.compareTo(count) == 1)//有价格才添加航班信息
                                {
                                    finfo.ListCabinInfo.add(cinfo);
                                    //break;//只添加每个产品最低价格航班信息
                                }
                            }
                        }
                    }
                    //添加航班节点
                    response.ListGoFlightInfo.add(finfo);
                }
            }

            /*for (MoFlightInfo item : response.ListGoFlightInfo) {
                MoCabinInfo moCabinInfo;
                for (int i = 0; i < item.ListCabinInfo.size() - 1; i++) {
                    for (int j = 0; j < item.ListCabinInfo.size() - i - 1; j++) {
                        if (item.ListCabinInfo.get(j + 1).CallCenterAmountInfo.OrgTicketAmount.compareTo(item.ListCabinInfo.get(j).CallCenterAmountInfo.OrgTicketAmount) == -1) {
                            moCabinInfo = item.ListCabinInfo.get(j);
                            item.ListCabinInfo.set(j, item.ListCabinInfo.get(j + 1));
                            item.ListCabinInfo.set(j + 1, moCabinInfo);
                        }
                    }
                }
            }
            MoFlightInfo MoFlightInfo;
            for (int i = 0; i < response.ListGoFlightInfo.size() - 1; i++) {
                for (int j = 0; j < response.ListGoFlightInfo.size() - i - 1; j++) {
                    if (response.ListGoFlightInfo.get(j + 1).ListCabinInfo.get(0).CallCenterAmountInfo.OrgTicketAmount.compareTo(response.ListGoFlightInfo.get(j).ListCabinInfo.get(0).CallCenterAmountInfo.OrgTicketAmount) == -1) {
                        MoFlightInfo = response.ListGoFlightInfo.get(j);
                        response.ListGoFlightInfo.set(j, response.ListGoFlightInfo.get(j + 1));
                        response.ListGoFlightInfo.set(j + 1, MoFlightInfo);
                    }
                }
            }
            response.IsSuccess = true;*/

//            for (MoFlightInfo a : response.ListGoFlightInfo)
//            {
            /*response.ListGoFlightInfo.forEach(a -> a.ListCabinInfo.Sort(delegate(Flight.Product.MoClass.MoFlightSearchResponse.MoCabinInfo x, Flight.Product.MoClass.MoFlightSearchResponse.MoCabinInfo y)
            { return x.CallCenterAmountInfo.OrgTicketAmount.CompareTo(y.CallCenterAmountInfo.OrgTicketAmount); }
                ));*/
//            }

            response.IsSuccess = true;
        } catch (Exception ex) {
            response.ErrorCode = (EnumHelper.ReturnCode.系统异常代码).toString();
            ex.printStackTrace();
            return response;
        }

        return response;

    }

    /**
     * 获取token
     *
     * @return
     */
    private String _GetToken() throws IOException {
        String jsonParemt = "";
        String token = "";
        String tokenCacheKey = "_DRToken_"; //缓存中的key值
        Date requestTime = new Date();
        Date returnTime = new Date();
        String strMsg = "";
        String strToken = "";
        try {
            //此处获取缓存中的token ,根据key获取对应的token值
            /*Object cacheObject = redisService.getCacheObject(DR_TOKEN_KEY);
            if (cacheObject != null) {
                return token = (String) cacheObject;
            } else {*/
            jsonParemt = String.format("username=" + username + "&password=" + password + "&grant_type=" + grant_type);
            Map<String, String> mapRequest = new HashMap<>();
            mapRequest.put("username", username);
            mapRequest.put("password", password);
            mapRequest.put("grant_type", grant_type);
            strToken = HttpClientUtil.getResult(urlDR + "token", "", null, null, "application/json;charset=UTF-8", "post", jsonParemt, 60 * 1000, false);


                /*jsonParemt = String.format("username=%s&password=%s&grant_type=%s", username, password, grant_type);
                strToken = HttpClientUtil.getResult(urlDR + "token", "", null, null, "application/x-www-form-urlencoded", "post", jsonParemt, 60 * 1000, false);*/
            DrToken drToken = JSON.parseObject(strToken, DrToken.class);
            token = drToken.Access_token;
            _token_type = drToken.Token_type;

             /*   //将获取到的token缓存到Redis中
                if(token!=null && token.length()>0){
                    redisService.setCacheObject(DR_TOKEN_KEY, token,5L, TimeUnit.MINUTES);
                }

            }*/
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return token;
    }

    /**
     * String转Date
     */
    private Date convertToDate(String str) {
        Date date = null;
        if (str != null) {
            str = str.substring(11, 16);
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            try {
                date = sdf.parse(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return date;
    }

    /**
     * Date转String
     */
    private String convertToString(Date time) {
        String dateStr = "";
        if (time != null) {
            DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                dateStr = sdf.format(time);
                System.out.println(dateStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return dateStr;
    }

    /**
     * 获取字段长度
     */
    public int getWordCount(String OrderID) {

        OrderID = OrderID.replaceAll("[^\\x00-\\xff]", "**");
        int length = OrderID.length();
        return length;
    }

    /**
     * 舱位验价
     *
     * @return
     */
    @Override
    public MoFlightCheckResponse _FlightCheck(MoFlightCheckRequest moRequest) {
        //moRequest.OnlyCode = moRequest.OnlyCode;
        MoFlightCheckResponse response = new MoFlightCheckResponse();
//        response.OnlyCode = moRequest.OnlyCode;
//        response.ProviderCode = moRequest.ProviderCode;
//        response.RequestType = moRequest.RequestType;

        String strRequestData = "";
        String strResponseData = "";
        Date requestTime = new Date();
        Date returnTime = new Date();

        String tokenKey = null;
        try {
            tokenKey = this._GetToken();
        } catch (IOException e) {
            e.printStackTrace();
        }
        DrToken drToken = new DrToken(tokenKey, _token_type);
        try {

            //请求参数
            SearchPriceVo searchPriceVo = new SearchPriceVo();
            searchPriceVo.QueryResultId = moRequest.PolicyID;
            searchPriceVo.FlightNo = moRequest.FlightNo;
            searchPriceVo.Departure = moRequest.OrgAirport;
            searchPriceVo.Arrival = moRequest.DstAirport;
            searchPriceVo.SeatCode = moRequest.Cabin;
            searchPriceVo.RouteIndex = 0;
            searchPriceVo.ProductCode = moRequest.ProductType;

            Map<String, Object> objectToMap = getObjectToMap(searchPriceVo);
            StringBuffer buffer = null;
            if (objectToMap != null) {
                Iterator<String> it = objectToMap.keySet().iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    Object value = objectToMap.get(key);
                    if (buffer == null) {
                        buffer = new StringBuffer();
                    } else {
                        buffer.append("&");
                    }
                    buffer.append(key);
                    buffer.append("=");
                    buffer.append(value);
                }
            }

            strRequestData = buffer.toString();

            drToken.ServerUrl = urlDR + "TicketBooking/GetSelectFlightFromOTA";
            strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", drToken.Token_type, drToken.Access_token, "application/x-www-form-urlencoded", "post", strRequestData, 60 * 1000, false);

            returnTime = new Date();

            if (Strings.isNullOrEmpty(strResponseData)) {
                response.ErrorCode = (EnumHelper.ReturnCode.请求接口异常).toString();
                response.ErrorMsg = "舱位验价，未返回数据";
                response.IsSuccess = false;
                return response;
            }

            // 判断是否是基类错误
            DrResponsestatus baseResponse = JSON.parseObject(strResponseData, DrResponsestatus.class);
            if (!baseResponse.IsSuccess) {
                response.ErrorCode = (EnumHelper.ReturnCode.失败).toString();
                response.ErrorMsg = baseResponse.Msg;
                response.IsSuccess = false;
                return response;
            }

            // 获取选中航班实体处理
            DrFlightCheck drResponse = JSON.parseObject(strResponseData, DrFlightCheck.class);
            if (drResponse.IsSuccess) {
                if (drResponse.Data.SelectSegmentList.size() > 0) {
                    for (SelectSegmentList item : drResponse.Data.SelectSegmentList) {
                        response.PolicyID = item.ProductType;
                        if (item.AdultFare != null)
                            response.TicketAmount = item.AdultFare.Price;
                    }
                    //response.PolicyID = moRequest.PolicyID;
                    //瑞丽没返回舱位数量，验价验舱通过，直接默认9
                    if (response.IsSuccess && response.SeatCount <= 0) {
                        response.SeatCount = 9;
                    }
                    response.IsSuccess = true;
                } else {
                    response.ErrorCode = (EnumHelper.ReturnCode.失败).toString();
                    response.ErrorMsg = "舱位已售完！";
                    response.IsSuccess = false;
                    return response;
                }
            } else if (!drResponse.IsSuccess) {
                // 错误的
                response.ErrorCode = (EnumHelper.ReturnCode.失败).toString();
                if (drResponse.Msg != null) {
                    response.ErrorMsg = drResponse.Msg;
                }
                response.IsSuccess = false;
            }
        } catch (Exception ex) {
            response.ErrorCode = (EnumHelper.ReturnCode.系统异常代码).toString();
            ex.printStackTrace();
            return response;
        } finally {
        }
        return response;
    }

    /**
     * 瑞丽航班预订
     */

    @Override
    public MoCreateOrderResponse _OrderCreate(MoCreateOrderRequest moCreateOrderRequest) {
        moCreateOrderRequest.OnlyCode = moCreateOrderRequest.OnlyCode;

        MoCreateOrderResponse moCreateOrderResponse = new MoCreateOrderResponse();

        moCreateOrderResponse.RequestType = EnumHelper.RequestType.DR;
        moCreateOrderResponse.OnlyCode = moCreateOrderRequest.OnlyCode;

        Date RequestTime = null;
        Date ReturnTime = null;

        String strRequestData = "", strResponseData = "", strRequestData_Submit = "", strResponseData_Submit = "";

        String tokenKey = null;
        try {
            tokenKey = this._GetToken();
        } catch (IOException e) {
            e.printStackTrace();
        }
        DrToken drToken = new DrToken(tokenKey, _token_type);
        drToken.ServerUrl = urlDR + "TicketBooking/BookingOrderFromOTA";

        try {
            moCreateOrderRequest.Contacts.ContactMobile = "17710180782";
            // 验证
            MoSegment goSegment = moCreateOrderRequest.ListGoSegment.get(0);
            MoPassenger moPassenger = moCreateOrderRequest.ListMoPassenger.get(0);

            if (Integer.parseInt(String.valueOf(moPassenger.TicketAmount)) <= 0) {
                moCreateOrderResponse.ErrorMsg = "票价必须大于0";
                moCreateOrderResponse.ErrorCode = (EnumHelper.ReturnCode.请求参数为空).toString();
                moCreateOrderResponse.IsSuccess = false;
                return moCreateOrderResponse;
            }

            // 请求
           /* int len = getWordCount(moCreateOrderRequest.OrderID);
            System.out.println(moCreateOrderRequest.OrderID);*/
            // 乘机人信息
            List<BookingPassenger> bookingPassengerList = new ArrayList<>();
            //保险信息
            //List<BookingPassengerInsuranceList> insuranceList = new List<BookingPassengerInsuranceList>()
            //{
            //    new BookingPassengerInsuranceList()
            //    {
            //        InsuranceCode=0,
            //        Price=20
            //     }
            //};
            // 联系人信息
            BookingContact contactInfo = new BookingContact();
            contactInfo.ContactName =  BookingContactInfo.ContactName;
            contactInfo.MobilePhone = BookingContactInfo.MobilePhone;
            contactInfo.Email = BookingContactInfo.Email;
            contactInfo.AreaCode = BookingContactInfo.AreaCode;


            BookingExpress bExpress = new BookingExpress();
            int adultNum = 1;//成人序号
            int infantNum = 1;//婴儿序号
            for (MoPassenger ps : moCreateOrderRequest.ListMoPassenger) {
                // 测试用
                //if ( !("测试曾宪明".Equals( ps.PassengerName ) || "测试潘安".Equals( ps.PassengerName ) || "测试甜甜".Equals( ps.PassengerName )) )
                //{
                //    moCreateOrderResponse.ErrorCode = ( (int)EnumHelper.ReturnCode.失败 ).ToString();
                //    moCreateOrderResponse.ErrorMsg = ps.PassengerName + "是非法的测试乘客名称！！！";
                //    moCreateOrderResponse.IsSuccess = false;
                //    return moCreateOrderResponse;
                //}

                String travelerCategory = "Adult";
                if (ps.PassengerType == 2) {
                    travelerCategory = "Child";
                } else if (ps.PassengerType == 3) {
                    travelerCategory = "Infant";
                }


                BookingPassenger info = new BookingPassenger();


                //public enum ETicketIdTypeId : int { 无证件 = 0, 身份证 = 1, 军人证 = 2, 学生证 = 3,
                //护照 = 4, 港澳居民来往内地通行证 = 5, 其他证 = 6,
                //台湾居民来往大陆通行证 = 7, 驾驶证 = 8, 港澳通行证 = 9, 户口本 = 10, 出生证明 = 11, 台湾通行证 = 12, 永久居留身份证 = 13,
                //港澳台居民居住证 = 14, 其他证件 = 99 }


                String idType = "NI";
                if (new Date().compareTo(convertToDate("2021-02-07 17:00")) == 1) {
                    if (ps.IDNO.trim().length() >= 18) {
                        if (PublicClass.CheckIDCard(ps.IDNO)) {
                            idType = "NI"; //身份证
                        } else {
                            idType = "ID"; //其他
                        }
                    } else {
                        if (ps.IDType == 2) {
                            idType = "ID04";
                        }
                        if (ps.IDType == 3) {
                            idType = "ID18";
                        }
                        if (ps.IDType == 4) {
                            idType = "PP";
                        }
                        if (ps.IDType == 5) {
                            idType = "ID13";
                        }
                        if (ps.IDType == 6 || ps.IDType == 99 || ps.IDType == 8) {
                            idType = "ID";
                        }
                        if (ps.IDType == 7) {
                            idType = "ID14";
                        }
                        if (ps.IDType == 9) {
                            idType = "ID02";
                        }
                        if (ps.IDType == 10) {
                            idType = "NI03";
                        }
                        if (ps.IDType == 11) {
                            idType = "ID17";
                        }
                        if (ps.IDType == 12) {
                            idType = "ID03";
                        }
                        if (ps.IDType == 13) {
                            idType = "ID16";
                        }
                        if (ps.IDType == 14) {
                            idType = "NI02";
                        }
                        //护照 = 4, 港澳居民来往内地通行证 = 5, 其他证 = 6,
                        //台湾居民来往大陆通行证 = 7, 驾驶证 = 8, 港澳通行证 = 9, 户口本 = 10, 出生证明 = 11,
                        //台湾通行证(大陆居民往来台湾通行证) = 12, 永久居留身份证 = 13,
                        //港澳台居民居住证 = 14, 其他证件 = 99 }

                    }
                } else {
                    if (ps.IDType == 1) {
                        idType = "NI";
                    } else {
                        if (ps.IDType == 4) {
                            idType = "PP";
                        } else {
                            idType = String.valueOf(ps.IDType);
                        }
                    }
                }

                info.CertificateType = idType;
                info.PassengerType = travelerCategory;
                info.PassengerName = ps.PassengerName;
                info.CertificateNo = ps.IDNO;
                info.MobilePhone = Long.parseLong(ps.PassengerMobile);
                info.BirthDay = convertToString(ps.Birthday);
                info.PassengerIndex = adultNum;
                if (ps.PassengerType != 3)
                    info.InfantAdultBind = null;
                else {
                    info.InfantAdultBind = adultNum - infantNum;
                    infantNum++;
                }
                info.AddToCommonUser = false;

                bookingPassengerList.add(info);
                adultNum++;
            }

            // 请求数据
            OrderBookingSubmitVo vo = new OrderBookingSubmitVo();

            //预订航段信息
            BookingSegment bookingSegment = new BookingSegment();
            bookingSegment.QueryResultId = moCreateOrderRequest.PolicyID;
            bookingSegment.FlightNo = goSegment.FlightNo;
            bookingSegment.Departure = goSegment.OrgAirport;
            bookingSegment.Arrival = goSegment.DstAirport;
            bookingSegment.SeatCode = goSegment.Cabin;
            bookingSegment.RouteIndex = 0; //航段序号
            bookingSegment.ProductCode = goSegment.ProductType;

            List<BookingSegment> segments = new LinkedList<>();
            segments.add(bookingSegment);
            vo.BookingSegmentInfo = segments;

            //预订乘客信息
            vo.BookingPassengerList = bookingPassengerList;

            //预订联系人信息
            vo.BookingContactInfo = contactInfo;

            //积分抵扣信息
            vo.MpsPoint = new BigDecimal(0);

            //儿童价格选择类型
            vo.ChildFollowType = "Follow";
            //moCreateOrderRequest.ListMoPassenger.stream().anyMatch(a -> a.follow)?"Follow":"UnFollow";


            strRequestData = JSON.toJSONString(vo);
            strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", _token_type, drToken.Access_token, "application/json", "post", strRequestData, 60 * 1000, false);
            ReturnTime = new Date();
            if (Strings.isNullOrEmpty(strResponseData)) {
                moCreateOrderResponse.ErrorCode = (EnumHelper.ReturnCode.请求接口异常).toString();
                moCreateOrderResponse.ErrorMsg = "创建订单，未返回数据";
                moCreateOrderResponse.IsSuccess = false;
                return moCreateOrderResponse;
            }

            // 判断是否是基类错误
            DrResponsestatus baseResponse = JSON.parseObject(strResponseData, DrResponsestatus.class);
            if (!baseResponse.IsSuccess) {
                moCreateOrderResponse.ErrorCode = (EnumHelper.ReturnCode.失败).toString();
                moCreateOrderResponse.ErrorMsg = baseResponse.Msg;
                moCreateOrderResponse.IsSuccess = false;
                return moCreateOrderResponse;
            }

            // 后续逻辑处理
            DrBookingResult drCreateResponse = JSON.parseObject(strResponseData, DrBookingResult.class);
            if (!drCreateResponse.IsSuccess || drCreateResponse.Data == null) {
                moCreateOrderResponse.ErrorCode = (EnumHelper.ReturnCode.失败).toString();
                moCreateOrderResponse.ErrorMsg = drCreateResponse.Msg;
                moCreateOrderResponse.IsSuccess = false;
                return moCreateOrderResponse;

            }
            MoQueryOrderRequest queryOrder = new MoQueryOrderRequest();
            queryOrder.OrderID = drCreateResponse.Data.OrderId;

            MoQueryOrderResponse queryResponse = _QueryOrderInfo(queryOrder);
            MoOrderDetail od = new MoOrderDetail();
            od.OrderID = drCreateResponse.Data.OrderId;
            od.PayId = drCreateResponse.Data.PayId;
            od.PayTimeLimit = convertToDate(drCreateResponse.Data.PayLimit);
            od.OrderAction = drCreateResponse.Data.OrderAction;
            moCreateOrderResponse.ListMoOrderDetail.add(od);
            moCreateOrderResponse.MainOrderID = drCreateResponse.Data.OrderId;// 查询订单时，要传回该值
            moCreateOrderResponse.ExternalNo = drCreateResponse.Data.PayId;// 发起支付时，要传回该值
            moCreateOrderResponse.PayAmount = queryResponse.Amount;//应支付金额
            for (MoPayInfo item : queryResponse.ListPayInfo) {

                moCreateOrderResponse.SerialNumber = item.SwiftNumber;
            }
            moCreateOrderResponse.BigPnr = queryResponse.Pnr;

            moCreateOrderResponse.IsSuccess = true;
        } catch (Exception ex) {
            ex.printStackTrace();
            moCreateOrderResponse.ErrorCode = (EnumHelper.ReturnCode.系统异常代码).toString();
        }
        return moCreateOrderResponse;
    }

    /**
     * 瑞丽订单取消接口
     */
    @Override
    public MoCancelOrderResponse _CancelOrder(MoCancelOrderRequest request) {
        MoCancelOrderResponse response = new MoCancelOrderResponse();
        response.RequestType = EnumHelper.RequestType.DR;
        response.OnlyCode = request.OnlyCode;

        String strResponseData = "";
        Date requestTime = new Date();
        Date returnTime = new Date();
        String tokenKey = null;
        try {
            tokenKey = this._GetToken();
        } catch (IOException e) {
            e.printStackTrace();
        }
        DrToken drToken = new DrToken(tokenKey, _token_type);
        drToken.ServerUrl = urlDR + String.format("TicketOrder/CannelOrderFromOTA?ticketOrderId=" + request.ListOrderItem.OrderID);
        try {
            // 验证
            //验证token
            if (Strings.isNullOrEmpty(drToken.Access_token)) {
                response.ErrorMsg = EnumHelper.ReturnCode.失败.toString();
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                response.IsSuccess = false;
                return response;
            }
            if (com.ktgj.common.core.utils.StringUtils.isEmpty(request.ListOrderItem.OrderID)) {
                response.ErrorMsg = EnumHelper.ReturnCode.请求参数为空.toString();
                response.ErrorCode = EnumHelper.ReturnCode.请求参数为空.toString();
                response.IsSuccess = false;
                return response;
            }

            strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", drToken.Token_type, drToken.Access_token, "application/json", "Post", "", 60 * 1000, false);
            returnTime = new Date();
            if (Strings.isNullOrEmpty(strResponseData)) {
                response.ErrorCode = EnumHelper.ReturnCode.请求接口异常.toString();
                response.ErrorMsg = "取消失败，未返回数据";
                response.IsSuccess = false;
                return response;
            }

            // 判断是否是基类错误
            DrCancelOrder baseResponse = JSON.parseObject(strResponseData, DrCancelOrder.class);
            if (!baseResponse.IsSuccess) {
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                response.ErrorMsg = baseResponse.Msg;
                response.IsSuccess = false;
                return response;
            } else {
                response.ErrorCode = EnumHelper.ReturnCode.成功.toString();
                response.ErrorMsg = baseResponse.Msg;
                response.IsSuccess = true;
            }

        } catch (Exception ex) {
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            ex.printStackTrace();
            return response;
        } finally {
        }

        return response;
    }

    /**
     * 瑞丽订单出票接口
     */
    public MoAutoPayOutTickeResponse _AutoPayOutTicket(MoAutoPayOutTicketRequest request) throws IOException {
        MoAutoPayOutTickeResponse response = new MoAutoPayOutTickeResponse();
        response.RequestType = EnumHelper.RequestType.DR;
        response.OnlyCode = request.OnlyCode;

        String strResponseData = "";
        Date requestTime = new Date();
        Date returnTime = new Date();
        String tokenKey = this._GetToken();
        DrToken drToken = new DrToken(tokenKey, _token_type);
        drToken.ServerUrl = urlDR + String.format("TicketOrder/BookIssueTicketFromOTA?ticketOrderId=" + request.OrderID);
        try {
            // 验证
            //验证token
            if (Strings.isNullOrEmpty(drToken.Access_token)) {
                response.ErrorMsg = EnumHelper.ReturnCode.失败.toString();
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                return response;
            }
            if (Strings.isNullOrEmpty(request.OrderID)) {
                response.ErrorMsg = EnumHelper.ReturnCode.请求参数为空.toString();
                response.ErrorCode = EnumHelper.ReturnCode.请求参数为空.toString();
                return response;
            }

            strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", drToken.Token_type, drToken.Access_token, "application/json", "Post", "", 60 * 1000, false);
            returnTime = new Date();
            if (Strings.isNullOrEmpty(strResponseData)) {
                response.ErrorCode = EnumHelper.ReturnCode.请求接口异常.toString();
                response.ErrorMsg = "订单出票失败，未返回数据";
                response.IsSuccess = false;
                return response;
            }

            // 判断是否是基类错误
            DrCancelOrder baseResponse = JSON.parseObject(strResponseData, DrCancelOrder.class);
            if (!baseResponse.IsSuccess) {
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                response.ErrorMsg = baseResponse.Msg;
                response.IsSuccess = false;
                return response;
            } else {
                response.ErrorMsg = baseResponse.Msg;
                response.IsSuccess = true;
            }

        } catch (Exception ex) {
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            ex.printStackTrace();
            return response;
        }
        return response;
    }

    /**
     * 支付订单
     */
    @Override
    public MoOrderPayResponse _OrderPay(MoOrderPayRequest moRequest) {
        moRequest.OnlyCode = moRequest.OnlyCode;

        MoOrderPayResponse response = new MoOrderPayResponse();
        response.OnlyCode = moRequest.OnlyCode;
        response.ProviderCode = moRequest.ProviderCode;
        response.RequestType = moRequest.RequestType;

        String strRequestData = "";
        String strResponseData = "";
        Date requestTime = new Date();
        Date returnTime = new Date();
        String tokenKey = null;
        try {
            tokenKey = this._GetToken();
        } catch (IOException e) {
            e.printStackTrace();
        }
        DrToken drToken = new DrToken(tokenKey, _token_type);
        drToken.ServerUrl = urlDR + "TicketOrder/PaySuccessIssueTicketFromOTA";

        try {

            MoQueryOrderRequest request = new MoQueryOrderRequest();
            request.OrderID = moRequest.OrderID;
            MoQueryOrderResponse orderResponse = this._QueryOrderInfo(request);
            String swiftNumber = orderResponse.ListPayInfo.get(0).SwiftNumber;
            String payId = orderResponse.ListPayInfo.get(0).payId;
            if (!Strings.isNullOrEmpty(swiftNumber)) {
                // 先调用汇付天下的支付接口
                _HuiFu hf = new _HuiFu(MerId);
                moRequest.OrderID = swiftNumber;
                MoOrderPayResponse hfres = hf._OrderPayment(moRequest);

                if (hfres.IsSuccess) { //支付成功
                    moRequest.PayId = hfres.PayInfo.TradeId; //支付平台交易流水号
                    response.PayInfo.TradeId = hfres.PayInfo.TradeId;
                } else {
                    response.ErrorCode = hfres.ErrorCode;
                    response.ErrorMsg = hfres.ErrorMsg;
                    return response;
                }
            }

            //验证
            if (Strings.isNullOrEmpty(moRequest.PayId)) {
                response.ErrorMsg = "支付流水号-不能为空";
                response.IsSuccess = false;
                return response;
            }


            //请求参数
            DrPaySuccessIssueTicketModel requestParms = new DrPaySuccessIssueTicketModel();
            requestParms.OrderNo = orderResponse.OrderID; //订单号
            requestParms.WebPayInfoId = payId;  //支付订单ID, 传递的是
            requestParms.ThirdPayName = "HuifuPay"; //支付平台名称
            requestParms.TotalFee = String.valueOf(moRequest.PayAmount); //支付金额
            requestParms.TransactionId = moRequest.PayId; //支付平台流水号，汇付支付完成后返回的流水号
            requestParms.DealTime = new Date().toString(); //支付时间

            strRequestData = JSON.toJSONString(requestParms);

            strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", _token_type, drToken.Access_token, "application/json", "post", strRequestData, 60 * 1000, false);

            returnTime = new Date();

            if (Strings.isNullOrEmpty(strResponseData)) {
                response.ErrorCode = EnumHelper.ReturnCode.请求接口异常.toString();
                response.ErrorMsg = "支付失败，未返回数据";
                response.IsSuccess = false;
                return response;
            }

            // 判断是否是基类错误
            DrResponsestatus baseResponse = JSON.parseObject(strResponseData, DrResponsestatus.class);
            if (!baseResponse.IsSuccess) {
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                response.ErrorMsg = baseResponse.Msg;
                response.IsSuccess = false;
                return response;
            }

            // 验价实体处理
            DrPaySuccessResponse drResponse = JSON.parseObject(strResponseData, DrPaySuccessResponse.class);
            if (drResponse.IsSuccess) {
                // 数据处理
                response.PayInfo.TradeId = moRequest.LeadsID;
                response.IsSuccess = true;
            }
        } catch (Exception ex) {
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            ex.printStackTrace();
            return response;
        } finally {
        }
        return response;
    }


    /**
     * 订单基本信息查询
     */
    @Override
    public MoQueryOrderResponse _QueryOrderInfo(MoQueryOrderRequest request) throws IOException {
        //用于区分明细查询还是快速查询
        if (request.QueryTicketNoOnly) {
            return _QueryFastOrderInfo(request);
        }
        MoQueryOrderResponse response = new MoQueryOrderResponse();
        response.RequestType = EnumHelper.RequestType.DR;
        response.OnlyCode = request.OnlyCode;

        String strResponseData = "";
        Date requestTime = new Date();
        Date returnTime = new Date();
        String tokenKey = this._GetToken();
        DrToken drToken = new DrToken(tokenKey, _token_type);
        drToken.ServerUrl = urlDR + String.format("TicketOrder/FastGetTicketOrderBaseInfoFromOTA?ticketOrderId=" + request.OrderID);
        try {
            //验证
            //验证token
            if (Strings.isNullOrEmpty(drToken.Access_token)) {
                response.ErrorMsg = EnumHelper.ReturnCode.失败.toString();
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                return response;
            }
            if (Strings.isNullOrEmpty(request.OrderID)) {
                response.ErrorMsg = EnumHelper.ReturnCode.请求参数为空.toString();
                response.ErrorCode = EnumHelper.ReturnCode.请求参数为空.toString();
                return response;
            }

            strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", _token_type, drToken.Access_token, "application/json", "Get", "", 60 * 1000, false);
            returnTime = new Date();
            DrOTAFastDetailTicketOrderModel drResponse = JSON.parseObject(strResponseData, DrOTAFastDetailTicketOrderModel.class);
            if (drResponse.IsSuccess) {
                if (drResponse.Data != null) {
                    OTAFastDetailTicketOrderModel resultItem = drResponse.Data;
                    //订单信息
                    response.OrderID = resultItem.OrderSerialNumber;
                    response.OrderStatus = _DROrderStatus(resultItem.Status);
                    response.OrderStatusMsg = resultItem.Status;
                    response.Amount = resultItem.TotalPrice;//订单金额
                    // 支付信息
                    for (OTAFastPayInfoModel item : resultItem.PayList) {
                        MoPayInfo moPayInfo = new MoPayInfo();
                        moPayInfo.PayStatus = _DROrderStatus(item.PayStatusCode);
                        if (moPayInfo.PayStatus == _DROrderStatus(item.PayStatusCode)) {
                            moPayInfo.PayAmount = item.PayPrice;
                            response.PayAmount = item.PayPrice;//实际支付金额
                        }
                        moPayInfo.PayStatusMsg = item.PayStatusCode;
                        moPayInfo.SwiftNumber = item.SerialNumber;//支付商户订单号用于支付的回传
                        moPayInfo.payId = String.valueOf(item.PayId);
                        response.ListPayInfo.add(moPayInfo);
                    }

                    // 乘机人信息
                    for (OTAFastDetailPnrModel pl : resultItem.PnrList) {
                        response.Pnr = String.valueOf(pl.ID);//pnr唯一标识
                        //乘机人信息
                        List<OTAFastDetailPassengerModel> passengerInfo = pl.PassengerList;
                        for (OTAFastDetailPassengerModel item : passengerInfo) {
                            if (item == null) {
                                continue;
                            }
                            MoPassenger mopassenger = new MoPassenger();
                            //乘机人名
                            mopassenger.PNR = String.valueOf(pl.ID);//儿童与成人不在同一舱位会出现多个PNR
                            mopassenger.PassengerName = item.PASSENGER_NAME;
                            mopassenger.IDNO = item.CERTIFICATE_NO;

                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            mopassenger.Birthday = sdf.parse(item.BIRTH);
                            mopassenger.PsgID = String.valueOf(item.ID);
                            mopassenger.TicketNo = "";
                            response.ListMoPassenger.add(mopassenger);
                        }
                        for (OTAFastDetailLegModel lel : pl.LegList) {
                            MoSegment seg = new MoSegment();
                            if (lel.TicketList != null) {
                                for (OTAFastDetailTicketModel item : lel.TicketList) {
                                    //票号信息
                                    String ticketNo = item.TICKETNO;
                                    if (Strings.isNullOrEmpty(ticketNo)) {
                                        continue;
                                    }
                                    String passengerTicketStatus = item.TICKET_STATUS;
                                    if (!ticketNo.contains("-")) {
                                        StringBuilder builder = new StringBuilder();
                                        builder.append(ticketNo);
                                        builder.insert(3, "-");

                                        ticketNo = builder.toString();
                                    }
                                    MoPassenger mopassenger = response.ListMoPassenger.stream().filter(a -> a.PsgID.equals(String.valueOf(item.PASSENGERID))).findFirst().orElse(null);
                                    if (passengerTicketStatus.equals("C")) {
                                        TicketNoInfo tn = new TicketNoInfo();
                                        tn.TicketNo = ticketNo;
                                        mopassenger.ListTicketNoInfo.add(tn);
                                    } else {
                                        if (mopassenger.TicketNo != null && mopassenger.TicketNo.contains(ticketNo)) {
                                            continue;
                                        }
                                        mopassenger.TicketNo += ticketNo + ",";
                                    }
                                    mopassenger.TicketNo = Strings.isNullOrEmpty(mopassenger.TicketNo) ? "" : Pattern.compile("[\\,]").matcher(mopassenger.TicketNo).replaceAll("").trim();

                                    //判断出票状态
                                    if (Strings.isNullOrEmpty(mopassenger.TicketNo)) {
                                        mopassenger.Status = 301; //出票完成
                                    }

                                    seg.PrintPrice = item.TICKETPRICE;
                                    seg.OilFee = item.FUEL_TAX;
                                    seg.Tax = item.AIRPORT_TAX;
                                }

                            }
                            // 航段信息
                            seg.SegID = lel.ID;
                            seg.FlightNo = lel.FLIGHTNO;
                            seg.Cabin = lel.CLASSLEVEL;
                            seg.OrgAirport = lel.DEPARTURE;
                            seg.DstAirport = lel.ARRIVAL;
                            seg.DepDate = lel.TAKEOFF_TIME;
                            seg.ArrDate = lel.ARRIVE_TIME;
                            response.ListGoSegment.add(seg);
                        }
                    }
                }
                response.IsSuccess = true;
            } else {
                // 错误的
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                if (!drResponse.IsSuccess) {
                    response.ErrorMsg = drResponse.Msg;
                }
                response.IsSuccess = false;
            }

        } catch (Exception ex) {
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            ex.printStackTrace();
            return response;
        }
        return response;
    }

    /**
     * 订单明细查询
     *
     * @param request
     * @return
     */
    public MoQueryOrderResponse _QueryFastOrderInfo(MoQueryOrderRequest request) throws IOException {
        MoQueryOrderResponse response = new MoQueryOrderResponse();
        response.RequestType = EnumHelper.RequestType.DR;
        response.OnlyCode = request.OnlyCode;

        String strResponseData = "";
        Date requestTime = new Date();
        Date returnTime = new Date();
        String tokenKey = this._GetToken();
        DrToken drToken = new DrToken(tokenKey, _token_type);
        drToken.ServerUrl = urlDR + String.format("TicketOrder/GetTicketOrderDetailFromOTA?ticketOrderId=" + request.OrderID + "&pnrId=" + request.BigPnr);
        try {
            // 验证
            //验证token
            if (Strings.isNullOrEmpty(drToken.Access_token)) {
                response.ErrorMsg = EnumHelper.ReturnCode.失败.toString();
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                return response;
            }
            if (Strings.isNullOrEmpty(request.OrderID)) {
                response.ErrorMsg = EnumHelper.ReturnCode.请求参数为空.toString();
                response.ErrorCode = EnumHelper.ReturnCode.请求参数为空.toString();
                return response;
            }

            strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", _token_type, drToken.Access_token, "application/json", "Get", "", 60 * 1000, false);
            strResponseData = strResponseData.replaceAll("\"RefundPrice\":\"-\"", "\"RefundPrice\":\"0.0\"");
            returnTime = new Date();
            DrQueryResult drResponse = JSON.parseObject(strResponseData, DrQueryResult.class);
            if (drResponse.IsSuccess) {
                if (drResponse.Data != null) {
                    TicketOrderDetailModel resultItem = drResponse.Data;//订单信息
                    response.OrderID = resultItem.OrderSerialNumber;
                    response.ExternalNo = resultItem.PayId;
                    // 支付信息
                    for (TicketOrderDetailModelPay item : resultItem.PayOrders) {
                        MoPayInfo moPayInfo = new MoPayInfo();
                        moPayInfo.PayStatus = _DROrderStatus(item.PayStatusCode);
                        if (moPayInfo.PayStatus == _DROrderStatus(item.PayStatusCode)) {
                            moPayInfo.PayAmount = item.PayPrice;
                            response.serialNumber = item.SerialNumber;
                        }
                        response.ListPayInfo.add(moPayInfo);
                    }
                    //销售金额
                    response.Amount = resultItem.TotalPrice;

                    // 乘机人信息
                    for (TicketOrderDetailModelPassenger pl : resultItem.Passengers) {
                        if (pl == null) {
                            continue;
                        }
                        MoPassenger mopassenger = new MoPassenger();
                        //乘机人名
                        mopassenger.PassengerName = pl.PassengerName;
                        mopassenger.PsgID = String.valueOf(pl.Id);
                        mopassenger.TicketNo = pl.TicketNo;
                        response.ListMoPassenger.add(mopassenger);


                    }

                    // 航段信息
                    MoSegment seg = new MoSegment();
                    for (TicketOrderDetailModelFlight item : resultItem.Flights) {

                        seg.FlightNo = item.FlightNo;
                        seg.Cabin = item.ClassLevel;
                        seg.OrgAirport = item.Departure;
                        seg.DstAirport = item.Arrival;
                        seg.DepDate = new Date(item.TakeoffTime);
                        seg.ArrDate = new Date(item.ArriveTime);
                        seg.Airline = item.Airline;
                        seg.ProductType = item.ProductCode;
                    }
                    for (TicketOrderDetailModelRoute rt : resultItem.Routes) {
                        for (TicketOrderDetailModelRouteDetail item : rt.RouteDetails) {
                            seg.PrintPrice = item.TicketTotalPrice;
                            seg.OilFee = item.FuelTax;
                            seg.Tax = item.AirportTax;
                        }
                    }

                    response.ListGoSegment.add(seg);

                    //退票信息序列化
                    if (resultItem.Refunds != null && resultItem.Refunds.size() > 0) {
                        String refundsJson = JSON.toJSONString(resultItem.Refunds);
                        response.RefundsList = JSON.parseObject(refundsJson, new TypeReference<ArrayList<TicketOrderDetailRefundModel>>() {
                        });
                    }
                }
                response.IsSuccess = true;
            } else {
                // 错误的
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                if (!drResponse.IsSuccess) {
                    response.ErrorMsg = drResponse.Msg;
                }
                response.IsSuccess = false;
            }
        } catch (Exception ex) {
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            ex.printStackTrace();
            return response;
        }
        return response;
    }

    /**
     * 获取可操作航段
     *
     * @param moRequest
     * @return
     */
    public MoFlightSearchResponse _FlightChangeNotice(MoRescheduleSearchRequest moRequest) throws IOException {
        moRequest.OnlyCode = moRequest.OnlyCode;
        MoFlightSearchResponse response = new MoFlightSearchResponse();
        response.OnlyCode = moRequest.OnlyCode;
        response.ProviderCode = moRequest.ProviderCode;
        response.RequestType = moRequest.RequestType;

        String strResponseData = "";
        Date requestTime = new Date();
        Date returnTime = new Date();
        String tokenKey = this._GetToken();
        DrToken drToken = new DrToken(tokenKey, _token_type);
        drToken.ServerUrl = urlDR + String.format("TicketOrder/GetTicketOrderOperabilityLegFromOTA?ticketOrderId=" + moRequest.OrderID + "&pnrId=" + moRequest.PnrId);
        try {
            //验证
            //验证token
            if (Strings.isNullOrEmpty(drToken.Access_token)) {
                response.ErrorMsg = EnumHelper.ReturnCode.失败.toString();
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                return response;
            }
            if (Strings.isNullOrEmpty(moRequest.OrderID) || Strings.isNullOrEmpty(moRequest.PnrId)) {
                response.ErrorMsg = EnumHelper.ReturnCode.请求参数为空.toString();
                response.ErrorCode = EnumHelper.ReturnCode.请求参数为空.toString();
                return response;
            }
            //
            strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", _token_type, drToken.Access_token, "application/json", "Get", "", 60 * 1000, false);
            DrTicketOrderInfoChange drResponse = JSON.parseObject(strResponseData, DrTicketOrderInfoChange.class);
            if (drResponse.IsSuccess) {
                for (PnrLegChange item : drResponse.Data.LegList) {
                    // 改签查询结果
                    if (item != null) {
                        MoFlightInfo info = new MoFlightInfo();
                        info.FlightNo = String.valueOf(item.ID);
                        info.OrgAirport = item.DEPARTURE;
                        info.OrgAirportName = item.OrgCityName;
                        info.DstAirport = item.ARRIVAL;
                        info.DstAirportName = item.DstAirportName;

                        info.DepDate = new Date(item.TAKEOFF_TIME);
                        info.ArrDate = new Date(item.ARRIVETIME);
                        // 判断是否+1
                        if (info.ArrDate.getTime() < info.DepDate.getTime()) {

                            Calendar c = Calendar.getInstance();
                            c.setTime(info.ArrDate);
                            c.add(Calendar.DATE, 1);
                            Date newDate = c.getTime();

                            info.ArrDate = newDate;
                        }
                        info.FlightNo = item.FLIGHTNO;
                        info.Airline = item.AIRLINE;
                        info.Reschedule.Rernote = item.SeatClassDescription;
                        response.ListGoFlightInfo.add(info);
                    }
                    response.IsSuccess = true;
                }
            } else {
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                response.ErrorMsg = drResponse.Msg;
            }
        } catch (Exception ex) {
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            ex.printStackTrace();
            return response;
        } finally {
        }
        return response;
    }

    /**
     * TODO 不支持改签
     * 查询需要变更的航班
     */
    public MoFlightSearchResponse _SearchChangeDateFlightInfo(MoRescheduleSearchRequest moRequest) throws IOException {
        MoFlightSearchResponse response = new MoFlightSearchResponse();
        moRequest.OnlyCode = moRequest.OnlyCode;

        response.OnlyCode = moRequest.OnlyCode;
        response.ProviderCode = moRequest.ProviderCode;
        response.RequestType = moRequest.RequestType;

        String strRequestData = "";
        String strResponseData = "";
        Date requestTime = new Date();
        // 获取乘客唯一标识
        MoQueryOrderRequest tempRequest = new MoQueryOrderRequest();

        tempRequest.OnlyCode = response.OnlyCode;
        tempRequest.ProviderCode = response.ProviderCode;
        tempRequest.RequestType = response.RequestType;
        tempRequest.OrderID = moRequest.OrderID;

        MoQueryOrderResponse tempResponse = _QueryOrderInfo(tempRequest);
        String legIds = "";//航段唯一标识集合
        String passengerIds = "";//乘机人编码集合
        for (MoPassenger item : tempResponse.ListMoPassenger) {
            MoPassenger p = new MoPassenger();
            for (MoSegment gs : tempResponse.ListGoSegment) {
                legIds += String.format("legId=" + String.valueOf(gs.SegID) + "&");
            }
            passengerIds += String.format("passengerIds=" + item.PsgID + "&");
        }

        String toKenkey = this._GetToken();
        DrToken drToken = new DrToken(toKenkey, _token_type);
        drToken.ServerUrl = urlDR + "TicketChange/GetAvailableLegForChangeFromOTA";
        String date = data(moRequest.RescheduleFlightDepartDate, "yyyy/MM/dd"); //传递的格式
        String strParem = legIds + passengerIds + "flightDate=" + date;
        try {
            // 验证
            //验证token
            if (Strings.isNullOrEmpty(drToken.Access_token)) {
                response.ErrorMsg = EnumHelper.ReturnCode.失败.toString();
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                return response;
            }
            if (Strings.isNullOrEmpty(legIds) || Strings.isNullOrEmpty(passengerIds)) {
                response.ErrorMsg = EnumHelper.ReturnCode.请求参数为空.toString();
                response.ErrorCode = EnumHelper.ReturnCode.请求参数为空.toString();
                return response;
            }

            strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", _token_type, drToken.Access_token, "application/x-www-form-urlencoded", "post", strParem, 60 * 1000, false);
            DrLegBookingResponse drResponse = JSON.parseObject(strResponseData, DrLegBookingResponse.class);
            if (drResponse.IsSuccess) {
                requestTime = new Date();
                for (LegBooking item : drResponse.Data) {
                    if (item.SeatClassList.size() <= 0)
                        continue;
                    MoFlightInfo info = new MoFlightInfo();
                    info.OrgAirport = item.OrgCity;
                    info.DstAirport = item.DstCity;
                    info.DepTerm = item.DepartureTerminal;
                    info.ArrTerm = item.ArriveTerminal;

                    info.DepDate = item.DepartureTime;
                    info.ArrDate = item.ArriveTime;
                    // 判断是否+1
                    if (info.ArrDate.getTime() < info.DepDate.getTime())
                    {

                        Calendar c = Calendar.getInstance();
                        c.setTime(info.ArrDate);
                        c.add(Calendar.DATE, 1);
                        Date newDate = c.getTime();

                        info.ArrDate = newDate;
                    }
                    info.FlightNo = item.FlightNo;
                    info.AirportTax = moRequest.Tax;
                    info.FuelTax = moRequest.OilFee;
                    for (SeatClassBooking sc : item.SeatClassList) {

                        MoCabinInfo cinfo = new MoCabinInfo();
                        cinfo.Cabin = sc.SeatClassCode;

                        //正式环境没有此属性
                        //cinfo.BaseAmount = moRequest.Price.add(new BigDecimal(sc.UpgradeFee));

                        cinfo.CabinLeft = 9;//默认

                        // 改期信息赋值
                        cinfo.DiffPriceAdt = new BigDecimal(sc.UpgradeFee);
                        info.Reschedule.PID = item.QueryResultId;
                        cinfo.ChangeFeeAdt = new BigDecimal(sc.ChangeFee);

                        cinfo.ProductPolicy.PolicyId = item.QueryResultId;
                        cinfo.ProductPolicy.StrProductType = item.ProductCode;
                        info.ListCabinInfo.add(cinfo);
                    }
                    response.ListGoFlightInfo.add(info);

                }
                response.IsSuccess = true;
            } else {
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                response.ErrorMsg = drResponse.Msg;
            }
        } catch (Exception ex) {
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            ex.printStackTrace();
            return response;
        } finally {
        }
        return response;
    }

    /**
     * TODO 不支持改签
     * 提交变更
     */
    public MoOrderChangeResponse _OrderChange(MoOrderChangeRequest moRequest) throws IOException {
        MoOrderChangeResponse response = new MoOrderChangeResponse();
        moRequest.OnlyCode = moRequest.OnlyCode;

        response.OnlyCode = moRequest.OnlyCode;
        response.ProviderCode = moRequest.ProviderCode;
        response.RequestType = moRequest.RequestType;

        String strRequestData = "";
        String strResponseData = "";
        Date requestTime = new Date();
        // 获取乘客唯一标识
        MoQueryOrderRequest tempRequest = new MoQueryOrderRequest();

        tempRequest.OnlyCode = response.OnlyCode;
        tempRequest.ProviderCode = response.ProviderCode;
        tempRequest.RequestType = response.RequestType;
        tempRequest.OrderID = moRequest.OrderId;

        MoQueryOrderResponse tempResponse = _QueryOrderInfo(tempRequest);
        String legId = "";//航段唯一标识集合
        List<String> passengerIds = new ArrayList<String>();//乘机人编码集合
        for (MoPassenger item : tempResponse.ListMoPassenger) {
            MoPassenger p = new MoPassenger();
            for (MoSegment gs : tempResponse.ListGoSegment) {
                legId = String.valueOf(gs.SegID);
            }
            passengerIds.add(item.PsgID);
        }
        MoRescheduleSearchRequest ChangeRequest = new MoRescheduleSearchRequest();

        ChangeRequest.OnlyCode = response.OnlyCode;
        ChangeRequest.ProviderCode = response.ProviderCode;
        ChangeRequest.RequestType = response.RequestType;
        ChangeRequest.OrderID = moRequest.OrderId;

        MoFlightSearchResponse ChangeResponse = _SearchChangeDateFlightInfo(ChangeRequest);
        String queryResultId = "";
        String flightNo = "";
        String seatClass = "";
        String productCode = "";
        for (MoFlightInfo lg : ChangeResponse.ListGoFlightInfo) {
            for (MoCabinInfo item : lg.ListCabinInfo) {
                queryResultId = item.ProductPolicy.PolicyId;
                flightNo = moRequest.NewChangeAirOriDest.FlightNo;
                productCode = item.ProductPolicy.StrProductType;
                seatClass = moRequest.NewChangeAirOriDest.Cabin;
            }
        }
//        StrParam strParam = new StrParam();
//        strParam.legId = legId;
//        strParam.passengerIds = passengerIds;
//        strParam.queryResultId = queryResultId;
//        strParam.flightNo = flightNo;
//        strParam.productCode = productCode;
//        strParam.seatClass = seatClass;
//
//        strRequestData = JSON.toJSONString(strParam);


        DrToken drToken = new DrToken(this._GetToken(), _token_type);
        drToken.ServerUrl = urlDR + "TicketChange/ConfirmChangeFromOTA";
        try {
            strRequestData = JSON.toJSONString(moRequest);
            if (Strings.isNullOrEmpty(legId) || passengerIds.size() <= 0 || Strings.isNullOrEmpty(queryResultId) || Strings.isNullOrEmpty(flightNo) || Strings.isNullOrEmpty(productCode) || Strings.isNullOrEmpty(seatClass)) {
                response.ErrorMsg = EnumHelper.ReturnCode.请求参数为空.toString();
                response.ErrorCode = EnumHelper.ReturnCode.请求参数为空.toString();
                return response;
            }
            strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", _token_type, drToken.Access_token, "application/json", "Post", strRequestData, 60 * 1000, false);
            DrResponseChangeSegmentResult drResponse = JSON.parseObject(strResponseData, DrResponseChangeSegmentResult.class);
            if (drResponse.IsSuccess) {
                response.ApplicationId = drResponse.Data.OrderId;//jlx171018161430530
                response.ExternalNo = drResponse.Data.PayId;//212390
                response.ChangeId = drResponse.Data.PnrId;//5307917
                //response.PayAmount = Convert.ToDecimal( tsflight.allFee ) * moRequest.ChangePassenger.Count;
                response.IsSuccess = true;
            } else {
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                response.ErrorMsg = drResponse.Msg;
            }
        } catch (Exception ex) {
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            ex.printStackTrace();
            return response;
        } finally {
        }
        return response;
    }

    /**
     * 查询退票手续费
     */
    public MoOrderRefundCaltResponse _OrderRefundCalt(MoOrderRefundCaltRequest moRequest, boolean isSubsidy) throws IOException {
        isSubsidy = true;
        MoOrderRefundCaltResponse response = new MoOrderRefundCaltResponse();
        moRequest.OnlyCode = moRequest.OnlyCode;

        response.OnlyCode = moRequest.OnlyCode;
        response.ProviderCode = moRequest.ProviderCode;
        response.RequestType = moRequest.RequestType;

        String strRequestData = "";
        String strResponseData = "";
        Date requestTime = new Date();
        // 获取乘客唯一标识

        MoQueryOrderRequest tempRequest = new MoQueryOrderRequest();

        tempRequest.OnlyCode = response.OnlyCode;
        tempRequest.ProviderCode = response.ProviderCode;
        tempRequest.RequestType = response.RequestType;
        tempRequest.OrderID = moRequest.OutOrderID;

        MoQueryOrderResponse tempResponse = _QueryOrderInfo(tempRequest);
        String legIds = "";//航段唯一标识集合
        String passengerIds = "";//乘机人编码集合
        for (MoPassenger item : tempResponse.ListMoPassenger) {
            for (MoPassenger mp : moRequest.ListMoPassenger) {
                if (mp.TicketNo.replace("-", "").equals(item.TicketNo.replace("-", ""))) {
                    MoPassenger p = new MoPassenger();
                    for (MoSegment gs : tempResponse.ListGoSegment) {
                        legIds += String.format("legIds=" + String.valueOf(gs.SegID) + "&");
                    }
                    passengerIds += String.format("passengerIds={1}&", "passengerIds", item.PsgID);
                    p.PsgID = item.PsgID;
                    p.PassengerName = item.PassengerName;
                    p.TicketNo = item.TicketNo;
                    p.IDNO = item.IDNO;
                    p.Birthday = item.Birthday;
                    response.ListRefundPassenger.add(p);
                }

            }
        }

        DrToken drToken = new DrToken(this._GetToken(), _token_type);
        drToken.ServerUrl = urlDR + "TicketRefund/GetRefundPoundageFromOTA?" + legIds + StringUtils.removeEnd(passengerIds, "&");
        try {
            if (Strings.isNullOrEmpty(legIds) || Strings.isNullOrEmpty(passengerIds)) {
                response.ErrorMsg = EnumHelper.ReturnCode.请求参数为空.toString();
                response.ErrorCode = EnumHelper.ReturnCode.请求参数为空.toString();
                return response;
            }
            strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", _token_type, drToken.Access_token, "application/json", "Get", strRequestData, 60 * 1000, false);
            DrResponseCalculateRefundPoundage drResponse = JSON.parseObject(strResponseData, DrResponseCalculateRefundPoundage.class);
            if (drResponse.IsSuccess) {
                for (CalculateRefundPoundage item : drResponse.Data) {
                    MoPassenger moPassenger = response.ListRefundPassenger.stream().filter(a -> Objects.equals(a.PassengerName, item.PassengerName)).findFirst().orElse(null);
                    moPassenger.PassengerName = item.PassengerName;
                    moPassenger.RefundFee = item.RefundPoundage;
                    moPassenger.TicketAmount = item.TicketPayPrice;
                    moPassenger.AirportTax = item.AirportTax;
                    moPassenger.FuelTax = item.FuelTax;
                }
                response.IsSuccess = true;
            } else {
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                response.ErrorMsg = drResponse.Msg;
            }
        } catch (Exception ex) {
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            ex.printStackTrace();
            return response;
        } finally {
        }
        return response;
    }

    /**
     * 退票申请确认接口
     */
    public MoOrderRefundResponse _OrderRefund(MoOrderRefundRequest moRequest) throws IOException {
        moRequest.OnlyCode = moRequest.OnlyCode;

        MoOrderRefundResponse response = new MoOrderRefundResponse();
        response.OnlyCode = moRequest.OnlyCode;
        response.ProviderCode = moRequest.ProviderCode;
        response.RequestType = moRequest.RequestType;

        // 初始化日志信息

        String strRequestData = "";
        String strResponseData = "";
        Date requestTime = new Date();
        Date returnTime = new Date();
        // 获取乘客唯一标识
        MoQueryOrderRequest tempRequest = new MoQueryOrderRequest();

        tempRequest.OnlyCode = response.OnlyCode;
        tempRequest.ProviderCode = response.ProviderCode;
        tempRequest.RequestType = response.RequestType;
        tempRequest.OrderID = moRequest.OrderID;


        MoQueryOrderResponse tempResponse = _QueryOrderInfo(tempRequest);
        List<Long> legIds = new ArrayList<>();//航段唯一标识集合
        List<Long> passengerIds = new ArrayList<>();//乘机人编码集合
        List<String> passengerPnr = new ArrayList<>();//如果存在多个PNR需要分开提交退票申请
        Map<String, String> dicRefund = new Hashtable<>();//多个乘客多个航段处理
        for (MoPassenger mp : moRequest.ListMoPassenger) {
            for (MoPassenger item : tempResponse.ListMoPassenger) {
                if (mp.PassengerName.equals(item.PassengerName)) {//通过票号匹配多个乘客相对应的唯一标识
                    String strRefund = "";
                    if (!passengerPnr.contains(item.PNR))
                        passengerPnr.add(item.PNR);
                    MoPassenger p = new MoPassenger();
                    for (MoSegment gs : tempResponse.ListGoSegment) {
                        if (!legIds.contains(String.valueOf(gs.SegID)) && !dicRefund.containsKey(item.PNR)) {
                            legIds.add(Long.valueOf(gs.SegID));//获得航段唯一标识
                            strRefund += String.valueOf(gs.SegID) + "|";
                            break;
                        }
                    }
                    passengerIds.add(Long.valueOf(item.PsgID));
                    strRefund += String.valueOf(item.PsgID) + ",";

                    if (dicRefund.containsKey(item.PNR)) {
                        String dicValue = dicRefund.get(item.PNR);
                        dicValue += StringUtils.removeEnd(strRefund, ",");
                        dicRefund.replace(item.PNR, dicValue);
                    } else {
                        dicRefund.replace(item.PNR, StringUtils.removeEnd(strRefund, ","));
                    }
                }

            }

        }
        DrToken drToken = new DrToken(this._GetToken(), _token_type);
        drToken.ServerUrl = urlDR + "TicketRefund/RefundLegTicketFromOTA";
        try {
            if (legIds.size() <= 0 || passengerIds.size() <= 0) {
                response.ErrorMsg = EnumHelper.ReturnCode.请求参数为空.toString();
                response.ErrorCode = EnumHelper.ReturnCode.请求参数为空.toString();
                return response;
            }
            //String reason = moRequest.RefundType == Integer.parseInt(String.valueOf(EnumHelper.RefundType.RefundType1)) ? "" : Enum(typeof(EnumHelper.RefundType), moRequest.RefundType);

            String reason = "";

            if (moRequest.RefundType == 2) {
                reason = "肺炎疫情，申请全退";
            }

            //if (moRequest.ListMoPassenger.Exists(a => a.PassengerName == "测试"))
            //{
            //    reason = "OTA旗舰店测试票";
            //}
            String RefundMsg = "";
            for (int i = 0; i < passengerPnr.size(); i++) {
                /*Object pramStr = new Object();*/
                RefundModel refundModel = null;
                if (passengerPnr.size() == 1)//一个PNR多个乘客
                {
                    refundModel = new RefundModel();
                    refundModel.legIds = legIds;
                    refundModel.passengerIds = passengerIds;
                    refundModel.reason = reason;

                } else//多个个PNR多个乘客
                {
                    String refundRequest = dicRefund.get(passengerPnr.get(i));
                    String[] strArr = refundRequest.split("|");
                    String legIdsStr = strArr[0];//航段编码
                    List<Long> passengerIdsList = new ArrayList<>();
                    String[] passengerIdArr = strArr[1].split(",");//乘客编码
                    for (int j = 0; j < passengerIdArr.length; j++) {
                        passengerIdsList.add(Long.valueOf(passengerIdArr[j]));
                    }
                    List<Long> legId = new ArrayList<>();
                    Long value = Long.valueOf(legIdsStr);
                    legId.add(value);
                    refundModel = new RefundModel();
                    refundModel.legIds =legId;
                    refundModel.passengerIds = passengerIdsList;
                    refundModel.reason = reason;
                }
                String strRequestDataNew = JSON.toJSONString(refundModel);
                strRequestData += strRequestDataNew;
                strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", _token_type, drToken.Access_token, "application/json", "Post", strRequestDataNew, 60 * 1000, false);

                returnTime = new Date();
                if (Strings.isNullOrEmpty(strResponseData)) {
                    response.ErrorCode = EnumHelper.ReturnCode.请求接口异常.toString();
                    response.ErrorMsg = "申请退票，未返回数据";
                    response.IsSuccess = false;
                    return response;
                }
                DrCancelOrder drResponse = JSON.parseObject(strResponseData, DrCancelOrder.class);


                if (!drResponse.IsSuccess) {  // 错误的
                    response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                    response.ErrorMsg = RefundMsg + String.format(drResponse.Msg + "退票参数信息：" + strRequestDataNew);
                    response.IsSuccess = false;
                    return response;
                } else {
                    RefundMsg += String.format(drResponse.Msg + "退票参数信息：" + strRequestDataNew);
                }
            }
            response.ErrorMsg = RefundMsg;
            response.IsSuccess = true;
        } catch (Exception ex) {
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            ex.printStackTrace();
            return response;
        } finally {
        }

        return response;
    }

    /**
     * 查询退改签规则
     */
    @Override
    public MoCabinTgqResponse _GetCabinTgq(MoCabinTgqRequest moRequest) throws IOException {

        moRequest.OnlyCode = moRequest.OnlyCode;
        MoCabinTgqResponse response = new MoCabinTgqResponse();
        response.OnlyCode = moRequest.OnlyCode;
        response.ProviderCode = moRequest.ProviderCode;
        response.RequestType = moRequest.RequestType;

        String strRequestData = "";
        String strResponseData = "";
        Date requestTime = new Date();
        Date returnTime = new Date();

        DrToken drToken = new DrToken(this._GetToken(), _token_type);
        drToken.ServerUrl = urlDR + String.format("TicketRefund/GetClassRefundChangeRuleDataFromOTA?depAirport=" + moRequest.OrgAirport + "&arrAirport=" + moRequest.DstAirport + "&classCode=" + moRequest.Cabin + "&price=" + moRequest.Price + "&flightdatetime=" + moRequest.DepDate + "&productCode=" + moRequest.ProductType + "&flightNo=" + moRequest.FlightNo + "&airline=" + moRequest.FlightNo.substring(0, 2));
        try {
            requestTime = new Date();
            strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", _token_type, drToken.Access_token, "application/json", "Get", "", 60 * 1000, false);
            returnTime = new Date();
            DrResponseChangeRuleModel qsResponse = JSON.parseObject(strResponseData, DrResponseChangeRuleModel.class);
            if (qsResponse.IsSuccess) {
                if (qsResponse.Data.ClassCode.contains(moRequest.Cabin)) {
                    //if (string.IsNullOrEmpty(qsResponse.Data.ClassDescription))
                    //{
                    String Ttext = "";//退票说明
                    String Gtext = "";//改期说明
                    String Qtext = "";//签转说明
                    String ChildTtext = "";//儿童退票说明
                    String ChildGtext = "";//儿童改期说明
                    String ChildQtext = "";//儿童签转说明
                    for (ClassRefundChangeRuleDetailModel item : qsResponse.Data.Rules) {
                        item.TimeLimit = item.TimeLimit.replace("<br/>", "");
                        if (item.AllowPassengerType.contains("成人")) {
                            BigDecimal RefundRate = new BigDecimal(0);
                            if (!Strings.isNullOrEmpty(item.RefundFee))
                                RefundRate = PerctangleToDecimal(item.RefundFee).multiply(moRequest.Price);
                            Ttext += item.TimeLimit + (RefundRate.compareTo(moRequest.Price) == -1 ? RefundRate.toString() + "元" : "") + "；";
                            BigDecimal ChangeRate = new BigDecimal(0);
                            if (!Strings.isNullOrEmpty(item.ChangeFee))
                                ChangeRate = PerctangleToDecimal(item.ChangeFee).multiply(moRequest.Price);
                            Gtext += item.TimeLimit + (ChangeRate.compareTo(moRequest.Price) == -1 ? ChangeRate.toString() + "元" : "") + "；";
                            ;
                            if (!Strings.isNullOrEmpty(item.Endorsement))
                                Qtext += item.TimeLimit + item.Endorsement;
                        }
                        if (item.AllowPassengerType.contains("儿童")) {
                            BigDecimal RefundRate = new BigDecimal(0);
                            if (!Strings.isNullOrEmpty(item.RefundFee))
                                RefundRate = PerctangleToDecimal(item.RefundFee).multiply(moRequest.Price);
                            ChildTtext += item.TimeLimit + (RefundRate.compareTo(moRequest.Price) == -1 ? RefundRate.toString() + "元" : "") + "；";
                            BigDecimal ChangeRate = new BigDecimal(0);
                            if (!Strings.isNullOrEmpty(item.ChangeFee))
                                ChangeRate = PerctangleToDecimal(item.ChangeFee).multiply(moRequest.Price);
                            ChildGtext += item.TimeLimit + (ChangeRate.compareTo(moRequest.Price) == -1 ? ChangeRate.toString() + "元" : "") + "；";
                            ;
                            if (!Strings.isNullOrEmpty(item.Endorsement))
                                ChildQtext += item.TimeLimit + item.Endorsement;
                        }
                        if (item.AllowPassengerType.contains("婴儿")) {

                        }

                    }
                    response.Ttext = StringUtils.removeEnd(Ttext, "；");
                    response.Gtext = StringUtils.removeEnd(Gtext, "；");
                    response.Qtext = StringUtils.removeEnd(Qtext, "；");
                    response.ChdTtext = StringUtils.removeEnd(ChildTtext, "；");
                    response.ChdGtext = StringUtils.removeEnd(ChildGtext, "；");
                    response.ChdQtext = StringUtils.removeEnd(ChildQtext, "；");
                    //}
                    //else
                    //    response.Ttext = qsResponse.Data.ClassDescription;
                } else {
                    response.Ttext = "以航司为准";
                    response.Gtext = "以航司为准";
                    response.Qtext = "以航司为准";
                    response.ChdTtext = "以航司为准";
                    response.ChdGtext = "以航司为准";
                    response.ChdQtext = "以航司为准";
                }
            } else {
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                response.ErrorMsg = qsResponse.Msg;
                response.IsSuccess = false;
            }
            response.IsSuccess = true;
        } catch (Exception ex) {
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            ex.printStackTrace();
            return response;
        } finally {
        }
        return response;
    }


    /**
     * 将百分比转换成小数
     *
     * @param perc
     * @return
     */
    public BigDecimal PerctangleToDecimal(String perc) {
        try {
            //string patt = @"/^(?<num>[\d]{1,})(%?)$/";
            //decimal percNum = Decimal.Parse( System.Text.RegularExpressions.Regex.Match( perc, patt ).Groups["num"].Value );
            //return percNum / (decimal)100;
            BigDecimal percentage = new BigDecimal(0);
            if (!Strings.isNullOrEmpty(perc)) {
                String strTemp = StringUtils.removeEnd(perc, "%");
                BigDecimal bigDecimal = new BigDecimal(strTemp);
                if (!Strings.isNullOrEmpty(bigDecimal.toString())) {
                    percentage = new BigDecimal(strTemp);
                } else {
                    percentage = null;
                }
                if (percentage.compareTo(new BigDecimal(0)) == 0)
                    percentage = new BigDecimal(1);
                else
                    percentage = percentage.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);

            }
            return percentage;
        } catch (Exception e) {
            e.printStackTrace();
            return new BigDecimal(1);
        }
    }

    /**
     * 获取退改签规则
     *
     * @param moRequest
     * @return
     */
    public DrResponseChangeRuleModel GetClassRefundChangeRuleDataFromOTA(MoCabinTgqRequest moRequest) throws IOException {

        moRequest.OnlyCode = moRequest.OnlyCode;
        DrResponseChangeRuleModel response = new DrResponseChangeRuleModel();
        response.OnlyCode = moRequest.OnlyCode;
        response.ProviderCode = moRequest.ProviderCode;
        response.RequestType = moRequest.RequestType;

        String strRequestData = "";
        String strResponseData = "";
        Date requestTime = new Date();
        Date returnTime = new Date();

        DrToken drToken = new DrToken(this._GetToken(), _token_type);
        try {
            if (!Strings.isNullOrEmpty(moRequest.FlightNo)) {
                requestTime = new Date();
                strResponseData = HttpClientUtil.getResult(drToken.ServerUrl, "", _token_type, drToken.Access_token, "application/json", "Get", "", 60 * 1000, false);
                drToken.ServerUrl = urlDR + String.format("TicketRefund/GetClassRefundChangeRuleDataByLegIdFromOTA?legId=" + moRequest.FlightNo);
                returnTime = new Date();
                DrResponseChangeRuleModel qsResponse = JSON.parseObject(strResponseData, DrResponseChangeRuleModel.class);
                if (qsResponse.IsSuccess) {
                    response.Data = qsResponse.Data;
                } else {
                    response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                    response.ErrorMsg = qsResponse.Msg;
                    response.IsSuccess = false;
                }
                response.IsSuccess = true;
            } else {
                response.ErrorCode = EnumHelper.ReturnCode.失败.toString();
                response.ErrorMsg = EnumHelper.ReturnCode.请求参数为空.toString();
                response.IsSuccess = false;
            }
        } catch (Exception ex) {
            response.ErrorCode = EnumHelper.ReturnCode.系统异常代码.toString();
            ex.printStackTrace();
            return response;
        } finally {
        }
        return response;
    }

    /**
     * 支付状态转换
     *
     * @param strDr
     * @return
     */
    private String GetPayStateConvert(String strDr) {
        switch (strDr) {
            case "WaitPay":
                return "等待支付";
            case "PaySuccess":
                return "支付成功";
            case "PayFail":
                return "支付失败";
            default:
                return strDr;
        }
    }

    private int _DROrderStatus(String status) {
        switch (status) {
            case "等待支付":
                return 101;
            case "支付成功":
                return 201;
            case "支付失败":
                return 202;
            case "等待出票":
                return 300;
            case "出票完成":
                return 301;
            case "出票失败":
                return 302;
            case "订单作废":
                return 0;
            default:
                return 1;
        }

    }

    /**
     * object转map
     *
     * @param obj
     * @return
     */
    public Map<String, Object> getObjectToMap(Object obj) {
        Map<String, Object> map = new LinkedHashMap<>();
        try {
            Class<?> clazz = obj.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                String fileName = field.getName();
                Object value = field.get(obj);
                if (value == null) {
                    value = "";
                }
                map.put(fileName, value);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return map;
    }

    //日期格式转字符串类型
    private String data(Date date, String str) {
        SimpleDateFormat format = new SimpleDateFormat(str);
        return format.format(date);
    }
}
